window.onload = function () {
    listCart();
}

function goToHome() {
    window.location.href = "index.jsp";
}


function submit() {
    var xhr = new XMLHttpRequest();
    xhr.open("POST", "http://localhost:8080/cart", true);
    xhr.setRequestHeader('Content-Type', 'application/json');

    var cart = JSON.parse(sessionStorage.getItem('cart')) || [];

    var username = getUserNameFromCookie();

    cart.forEach(item => {
        item.username = username;
    });

    xhr.send(JSON.stringify(cart));

    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
                window.alert("提交成功");
                clearCart();
            } else {
                window.alert("提交失败");
                console.error('请求失败，状态码：', xhr.status);
            }
        }
    };
}

function del(id) {
    var cart = JSON.parse(sessionStorage.getItem('cart')) || [];

    var index = cart.find(item => item.id === id);

    cart.splice(index, 1);
    sessionStorage.setItem('cart', JSON.stringify(cart));

    var oldTotal = document.getElementById('total').innerHTML;
    var price = document.getElementById(id).querySelectorAll('td')[8].innerHTML.substring(1);
    var newTotal = parseInt(oldTotal) - parseInt(price);

    document.getElementById('total').innerHTML = newTotal;
    document.getElementById('list').removeChild(document.getElementById(id));
}

function listCart() {
    var cart = sessionStorage.getItem('cart');
    var list = document.getElementById('list');
    cart = JSON.parse(cart);

    var totalPrice = 0;

    for (var i = 0; i < cart.length; i++) {
        var div = document.createElement('div');
        div.id = cart[i].id;
        div.className = 'item';
        var total = parseFloat(cart[i].price) * parseFloat(cart[i].amount);

        div.innerHTML = "<table><tr><th rowspan='2'><img src='img/" + cart[i].img
            + "'></th><td>名称</td><td>单价</td><td>数量</td><td>总价</td><td>操作</td></tr>"
            + "<tr><td>"
            + cart[i].title + "</td><td>"
            + cart[i].price + "</td><td>"
            + cart[i].amount + "</td><td>￥"
            + total.toFixed(2)
            + "</td><td><button onclick='del(" + cart[i].id
            + ")'>删除</button></td></tr></table>";

        list.appendChild(div);

        totalPrice += total;
    }

    document.getElementById('total').innerHTML = totalPrice.toFixed(2);
}

function clearCart(){
    sessionStorage.removeItem('cart');
    location.reload();
}